package com.lemox.security;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashCode
{
	
	public static final String ALGORITHM_SHA_1 = "SHA-1";
	public static final String ALGORITHM_MD5 = "MD5";
	
	public static String hash_sum (String str, String algorithm) throws NoSuchAlgorithmException
	{
		MessageDigest md = null;
		String sumStr = null;
		md = MessageDigest.getInstance(algorithm);
		byte[] digest = md.digest(str.getBytes());
		sumStr = com.lemox.security.HashCode.bytetoString(digest);
		return sumStr;
	}
	
	public static String sha1sum (String str) throws NoSuchAlgorithmException
	{
		String sumStr = null;
		sumStr = com.lemox.security.HashCode.hash_sum(str, com.lemox.security.HashCode.ALGORITHM_SHA_1);
		return sumStr;
	}
	
	public static String md5sum (String str) throws NoSuchAlgorithmException
	{
		String sumStr = null;
		sumStr = com.lemox.security.HashCode.hash_sum(str, com.lemox.security.HashCode.ALGORITHM_MD5);
		return sumStr;
	}
	
	
	// ------------------------------------------------------------------
	public static String bytetoString(byte[] digest)
	{
		String str = "";
		String tempStr = "";

		for (int i = 0; i < digest.length; i++)
		{
			tempStr = (Integer.toHexString(digest[i] & 0xff));
			if (tempStr.length() == 1)
			{
				str = str + "0" + tempStr;
			} else
			{
				str = str + tempStr;
			}
		}
		return str.toLowerCase();
	}
	
	/*
	 * 
	 * */
	public static boolean hex_approximate_equal(String hash_sum, String hash_sum_tmp, int max_approximate_value)
	{
		boolean flag = true;
		int shift_count = 0;
		if (hash_sum.length() != hash_sum_tmp.length())
		{
			// ---- System.out.println("not the same length");
			flag = false;
		}
		else
		{
			BigInteger big_hash_sum     = new BigInteger(hash_sum,16);
			BigInteger big_hash_sum_tmp = new BigInteger(hash_sum_tmp,16);
			shift_count = big_hash_sum.xor(big_hash_sum_tmp).bitCount();
			if (shift_count <= max_approximate_value)
			{
				flag = true;
			}
			else
			{
				flag = false;
			}
		}
		return flag;
	}
}

